package test01;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import test02.XmlUtils;

public class ReadStudentsXML {
    public static void main(String[] args) {
        // 解析 XML 文件，得到 Document 对象
        Document document = XmlUtils.getDocumentInstance("students.xml");

        // 获取根标签 <students>
        Element root = document.getDocumentElement();
        System.out.println("根标签: " + root.getTagName());
         // 获取所有 <student> 节点
        NodeList studentList = root.getElementsByTagName("student");

        // 遍历所有 student 节点
        for (int i = 0; i < studentList.getLength(); i++) {
            Element student = (Element) studentList.item(i); // 当前 <student> 元素

            // 获取属性 id 和 sex
            String id = student.getAttribute("id");
            String sex = student.getAttribute("sex");

            // 获取子标签内容
            String name = student.getElementsByTagName("name").item(0).getTextContent().trim();
            String age = student.getElementsByTagName("age").item(0).getTextContent().trim();
            String address = student.getElementsByTagName("address").item(0).getTextContent().trim();

            // 打印信息
            System.out.println("----------- 学生信息 -----------");
            System.out.println("ID: " + id);
            System.out.println("性别: " + sex);
            System.out.println("姓名: " + name);
            System.out.println("年龄: " + age);
            System.out.println("地址: " + address);
            System.out.println(i);
            System.out.println("*******************************");

        }
    }
}
